﻿#include <QCoreApplication>
#include <QDebug>

// 通信设备接口类
class Device
{
public:
    virtual void write() = 0;
    virtual void read() = 0;
};

///
/// 具体的子类，网口通信类
///
class EthernetDevice : public Device
{
public:
    EthernetDevice()
    {
        qDebug()<<"EthernetDevice construct";
    }

    virtual ~EthernetDevice()
    {
        qDebug()<<"EthernetDevice disconstruct";
    }

    virtual void write()
    {
        qDebug()<<"EthernetDevice write";
    }

    virtual void read()
    {
        qDebug()<<"EthernetDevice read";
    }
};

///
/// 具体的子类，串口通信类
///
class UartDevice: public Device
{
public:
    UartDevice()
    {
        qDebug()<<"uartDevice construct";
    }

    virtual ~UartDevice()
    {
        qDebug()<<"uartDevice disconstruct";
    }

    virtual void write()
    {
        qDebug()<<"uartDevice write";
    }

    virtual void read()
    {
        qDebug()<<"uartDevice read";
    }
};

//设备工厂，在工厂方法模式中，工厂也抽象成接口类，新增子类的同时，也需要一起新增工厂子类
class DeviceFactory
{
public:
    virtual Device* createDevice() = 0;
};

class EthernetFactory : public DeviceFactory
{
public:
    virtual Device* createDevice()
    {
         return (new EthernetDevice());
    }
};

class UartFactory: public DeviceFactory
{
public:
    virtual Device* createDevice()
    {
         return (new UartDevice());
    }
};


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    DeviceFactory* factory = new EthernetFactory;
    //DeviceFactory* factory = new UartFactory;//如果需要更换连接，只要create另外的类型即可，其他代码是不需要更改的

    Device* dev = factory->createDevice();


    dev->write();
    dev->read();
    //。。。


    return a.exec();
}
